import effectTypes from './effectTypes';
import proc from './proc';

// 支持外界传入 channel
function runTakeEffect(env, { channel = env.channel, pattern }, cb) {
  console.log('runTakeEffect');
  // 要把回调函数存起来，等到页面中  dispatch pattern的时候才执行 cb
  const matcher = (input) => input.type === pattern;
  channel.take(cb, matcher);
}

function runPutEffect() {
  console.log('runPutEffect');
}

function runCallEffect() {
  console.log('runCallEffect');
}

function runForkEffect(env, { channel = env.channel, fn, args }, cb) {
  console.log('runForkEffect');
  // 先执行 fn, fn是生成器函数
  const taskIterator = fn.apply(null, args);
  proc(env, taskIterator);
  cb();
}

const effectRunnerMap = {
  [effectTypes.TAKE]: runTakeEffect,
  [effectTypes.PUT]: runPutEffect,
  [effectTypes.CALL]: runCallEffect,
  [effectTypes.FORK]: runForkEffect,
};

export default effectRunnerMap;
